<?php

namespace control;
//日志类
class logClass extends adIndexClass
{
    private const title = '日志类';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'coid'          => [
                        'name'  => '账套',
                        'width' => 100,
                    ],
                    'menuOne'          => [
                        'name'  => '{l.log.homeSearch.menuOne}',
                        'width' => 150,
                    ],
                    'menuTwo'  => [
                        'name'  => '{l.log.homeSearch.menuTwo}',
                        'width' => 150,
                    ],
                    'menuThree'         => [
                        'name'  => '{l.log.homeSearch.menuThree}',
                        'width' => 150,
                    ],
                    'menuFour'          => [
                        'name'  => '四级导航',
                        'width' => 150,
                    ],
                    'staff'          => [
                        'name'  => '{l.log.homeSearch.staffName}',
                        'width' => 100,
                    ],
                    'text'          => [
                        'name'  => '{l.log.homeSearch.text}',
                        'width' => 650,
                    ],
                    'time'          => [
                        'name'  => '{l.log.homeSearch.time}',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    L('log.home.powerOne') => select(["name" => "powerOne", "option" => array_keys($this->powerAll), "change" => "getPowerTwo"]),
                    L('log.home.powerTwo')   => select(["name" => "powerTwo", "title" => "{l.log.home.powerTwo}", "change" => "getPowerThree"]),
                    L('role.home.powerThree') => select(["name" => "powerThree", "title" => "{l.role.home.powerThree}", "change" => "getPowerFour"]),
                ],
                [
                    '四级导航'  => select(["name" => "powerFour"]),
                    L('log.home.text') => text(array("name" => "text")),
                    L('log.home.startDay') => text(array("name" => "startDay", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ];
        if ($this->power("log", "seeAll")) {
            $array[0][] = [
                '员工' => $this->staffSelect(array("show" => 4))
            ];
        }
        $array[0][] = [
            '账套' => selectMultiple(array('name' => 'coid', 'table' => 'company', 'where' => " 1=1 order by time asc", 'title' => '请选择', 'sqlId' => 'coid', 'sqlField' => 'name'))
        ];
        //生成查询表单
        $html = $this->tableShow($array,1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表页-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power("log", "del")) {
            $button .= "<span onclick=\"layer('log','del',{})\" class='spanButton'>" . L('log.homeSearch.deletespan') . "</span>";
        }
        if (para('CSAIII') == '是') {
            $button .= "<span onclick=\"layer('log', 'edit', {})\" class='spanButton'>调整日志</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表页-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
            "text" => $this->post('text'),//详细说明
        ];
        //全等查询数组
        $equal = [
            'coid' => $this->post('coid'),
            'type' => $this->post('powerFour'),
            "stid" => $this->post('stid'),//目标对象
        ];
        $and   = "";
        //导航

        if (!empty($this->post('powerOne'))) {
            $power    = [];
            if($this->post('powerThree')){
                $powerOne = $this->post('powerOne');
                $powerTwo = $this->post('powerTwo');
                $powerThree= $this->post('powerThree');
                $power = array_keys($this->powerAll[$powerOne][$powerTwo][$powerThree]);
            }elseif($this->post('powerTwo')){
                $powerOne = $this->post('powerOne');
                $powerTwo = $this->post('powerTwo');
                foreach ($this->powerAll[$powerOne][$powerTwo] as $array) {
                    $power = array_merge($power,array_keys($array));
                }
            }else{
                $powerOne = $this->post('powerOne');
                foreach ($this->powerAll[$powerOne] as $twoArray) {
                    foreach ($twoArray as $array) {
                        $power = array_merge($power,array_keys($array));
                    }
                }
            }
            $and .= " and type in ( '" . implode("','", $power) . "' ) ";
        }
        //发生时间-开始日期
        if (!empty($this->post('startDay'))) {
            $data = explode('~', $this->post('startDay'));
            $start = trim($data[0]);
            //$end   = trim(end($data));
            $startDay = $start . " 00:00:00";
            $and      .= " and time >= '$startDay' ";
        }
        //记录时间-结束日期
        if (!empty($this->post('endDay'))) {
            $data = explode('~', $this->post('startDay'));
            //$start = trim($data[0]);
            $end   = trim(end($data));
            $endDay = $end . " 23:59:59";
            $and    .= " and time <= '$endDay' ";
        }
        //如果没有查看所有员工账户记录的权限
        if (!$this->power("log", "seeAll")) {
            $and .= " and stid = '" . $this->control['stid'] . "' ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page  = $this->page(["table" => "log", "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            $menuOne = $menuTwo = $menuThree =$menuFour= "";
            foreach ($this->powerAll as $oneKey => $twoArray) {
                foreach ($twoArray as $twoKey => $threeArray) {
                    foreach ($threeArray as $threeKey => $fourArray) {
                        if (isset($fourArray[$array['type']]['name']) && $fourArray[$array['type']]['name']) {
                            $menuFour = $fourArray[$array['type']]['name'];
                            $menuOne   = $oneKey;
                            $menuTwo   = $twoKey;
                            $menuThree   = $threeKey;
                        }
                    }
                }
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'coid':
                        $company = query("company", " coid = '$array[coid]' ");
                        $row[] = $company['coid'] ? $company['name'] : '';
                        break;
                    case 'menuOne':
                        $row[] = $menuOne;
                        break;
                    case 'menuTwo':
                        $row[] = $menuTwo;
                        break;
                    case 'menuThree':
                        $row[] = $menuThree;
                        break;
                    case 'menuFour':
                        $row[] = $menuFour;
                        break;
                    case 'staff':
                        $staff = query("staff", " stid = '$array[stid]' ");
                        $row[] = $staff['name'];
                        break;
                    case 'text':
                        $text  = $array['text'];
                        $row[] = $text;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*弹出层-删除日志*/
    public function del()
    {
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "{l.log.del.warmTips}" => "{l.log.del.warmTipsMsg}",
                ),
                [
                    must . '导航：' => select(["name" => "powerOne", "title" => "{l.role.home.powerOne}", "option" => array_keys($this->powerAll), "change" => "getPowerTwo"]) .
                        select(["name" => "powerTwo", "title" => "{l.role.home.powerTwo}", "change" => "getPowerThree"]) .
                        select(["name" => "powerThree", "title" => "{l.role.home.powerThree}"])
                ],
                [
                    must . '日志时间段：' => text(["name" => "start", "laydate" => ['type' => 'datetime'], 'class' => 'width200', "title" => "当前日志开始时间"]) . "-\n" .
                        text(["name" => "end", "laydate" => ['type' => 'datetime'], 'class' => 'width200', "title" => "当前日志结束时间"]),
                    must . '员工：' => selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '选择员工']),
                ],
                array(
                    must . "{l.log.del.password}" => password(array("name" => "password")),
                ),
            ),
        ));
        return $this->layer(array("title" => "{l.log.del.layTitle}", "height" => 300, "html" => $html));
    }

    /*异步处理-删除日志*/
    public function delEdit()
    {
        $field      = [
            'type'      => $this->post('powerThree'),
            'stid'      => $this->post('stid'),
            'startTime' => $this->post('start'),
            'endTime'   => $this->post('end'),
        ];
        $annotation = [
            'type'      => '导航',
            'stid'      => '员工',
            'startTime' => '日志开始时间',
            'endTime'   => '日志结束时间',
        ];
        $rules      = [
            'type'      => 'required',
            'stid'      => 'required',
            'startTime' => 'required|date',
            'endTime'   => 'required|date',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } elseif (empty($this->post('password'))) {
            $json['warn'] = L('log.delEdit.inputPassword');
            // $json['warn'] = "请填写你的登录密码";
        } elseif (verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = L('log.delEdit.passwordErr');
            // $json['warn'] = "登录密码输入有误";
        } else {
            $and = self::timeComparison($field['startTime'] . '~' . $field['endTime'], 'time');
            unset($field['startTime'], $field['endTime']);
            //统计日志数量
            $where = generateWhere($field) . $and;
            $num   = sqlNum("log", $where);
            //删除日志
            if ($num == 0) {
//                $json['warn'] = L('log.delEdit.noLog');
                 $json['warn'] = "此时间段一条日志都没有";
            } else {
                delete([
                    "table" => "log",
                    "where" => $where
                ]);
                //添加日志
                $text = $this->control['name'] . "删除了" . $num . "条关于时间段" . $this->post('start') . '~' . $this->post('end') . " 的日志";
                $this->logText(["type" => "log", "text" => $text]);
                //提示
                $_SESSION['warn'] = $this->control['name'] . "删除了" . $num . "条日志";
                $json['warn']     = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    public function edit()
    {
        $html = $this->layerEdit(array(
            "table" =>
                [
                    [
                        must . '导航：' => select(["name" => "powerOne", "title" => "{l.role.home.powerOne}", "option" => array_keys($this->powerAll), "change" => "getPowerTwo"]) .
                            select(["name" => "powerTwo", "title" => "{l.role.home.powerTwo}", "change" => "getPowerThree"]) .
                            select(["name" => "powerThree", "title" => "{l.role.home.powerThree}"])
                    ],
                    [
                        '员工：' => selectMultiple(["name" => "nowStid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width150', 'title' => '现有员工']) . '->' . selectMultiple(["name" => "expectStid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width150', 'title' => '期望员工']),
                    ],
                    [
                        must . '上班时间：' => text(["name" => "startTime", "laydate" => ['type' => 'time'], "title" => "上班时间", 'value' => '09:00:00']) . "-\n" .
                            text(["name" => "endTime", "laydate" => ['type' => 'time'], "title" => "上班时间", 'value' => '18:00:00'])
                    ],
                    [
                        must . '当前日志时间段：' => text(["name" => "nowStart", "laydate" => [], "title" => "当前日志时间段"]) . "-\n" .
                            text(["name" => "nowEnd", "laydate" => [], "title" => "当前日志时间段"])
                    ],
                    [
                        must . '期望日志时间段：' => text(["name" => "expectStart", "laydate" => [], "title" => "期望日志时间段"]) . "-\n" .
                            text(["name" => "expectEnd", "laydate" => [], "title" => "期望日志时间段"])
                    ],

                ],
        ));
        return $this->layer(["title" => "系统日志操作人及时间随机修改", "height" => 320, "html" => $html]);
    }

    public function editEdit()
    {
        $field      = [
            'powerThree'  => $this->post('powerThree'),
            'nowStid'     => $this->post('nowStid'),
            'stid'        => $this->post('expectStid'),
            'startTime'   => $this->post('startTime'),
            'endTime'     => $this->post('endTime'),
            'nowStart'    => $this->post('nowStart'),
            'nowEnd'      => $this->post('nowEnd'),
            'expectStart' => $this->post('expectStart'),
            'expectEnd'   => $this->post('expectEnd'),
        ];
        $annotation = [
            'powerThree'  => '导航',
            'nowStid'     => '现有员工',
            'stid'        => '期望员工',
            'startTime'   => '上班时间',
            'endTime'     => '下班时间',
            'nowStart'    => '当前日志开始时间',
            'nowEnd'      => '当前日志结束时间',
            'expectStart' => '期望日志开始时间',
            'expectEnd'   => '期望日志结束时间',
        ];
        $rules      = [
            'powerThree'  => 'required',
            //            'nowStid'     => 'required',
            //            'stid'        => 'required',
            'startTime'   => 'required',
            'endTime'     => 'required',
            'nowStart'    => 'required|date',
            'nowEnd'      => 'required|date',
            'expectStart' => 'required|date',
            'expectEnd'   => 'required|date',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            // 开始更新
            $result = find([
                'table' => 'log',
                'where' => static::timeComparison($field['nowStart'] . '~' . $field['nowEnd']) .
                    search([
                        '=' => [
                            'type' => $field['powerThree'],
                            'stid' => $field['nowStid']
                        ]
                    ])
            ]);
            $x      = 0;
            foreach ($result['array'] as $item) {
                $randomTime = date('Y-m-d', mt_rand(strtotime($field['expectStart']), strtotime($field['expectEnd']))) . ' ' . date('H:i:s', mt_rand(strtotime($field['startTime']), strtotime($field['endTime'])));
                $text       = '';
                if ($field['stid']) {
                    $nowName    = static::findStaff($item['stid']);
                    $expectName = static::findStaff($field['stid']);
                    $text       = str_replace($nowName, $expectName, $item['text']);
                }

                $warn = static::update([
                    'table' => 'log',
                    'field' => [
                        'text' => $text,
                        'stid' => $field['stid'],
                        'time' => $randomTime,
                    ],
                    'where' => " id = '$item[id]' "
                ], false);
                if ($warn === '更新成功') {
                    $x++;
                }
            }
            $_SESSION['warn'] = "已处理$x 条日志记录";
            $json['warn']     = 2;
        }
        //返回
        return json_encode($json, 320);
    }

}
